package com.example.springboot01.service.impl;

import com.example.springboot01.constant.Constants;
import com.example.springboot01.model.TokenModel;
import com.example.springboot01.service.TokenManageService;
import com.example.springboot01.utils.UUIDUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @Auther: zrd
 * @Date: 2022/6/13/06/13/0:26
 * @Description: com.example.springboot01.service.impl
 */
@Service
@Primary
public class TokenManageServiceRedisImpl implements TokenManageService {

    @Autowired
    RedisTemplate redisTemplate;
    //创建token
    @Override
    public String createToken(String userId, String userType) {
        String token = userId + "_" + userType + "_" + UUIDUtil.getUUID();
        redisTemplate.opsForValue().set(Constants.REDIS_PREFIX_TOKEN + userId,
                token, Constants.TOKEN_EXPIRED_TIME_MIN, TimeUnit.MINUTES);
        return token;
    }
    //校验token
    @Override
    public boolean checkToken(String token) {
        String userId = getUserIdFromToken(token);
        if (StringUtils.isEmpty(userId)){
            return false;
        }
        Object existToken = redisTemplate.opsForValue().get(Constants.REDIS_PREFIX_TOKEN + userId);
        if (existToken == null){
            return false;
        }
        if (!token.equals((String) existToken)){
            return false;
        }
        return true;
    }

    //解析token
    @Override
    public TokenModel extractToken(String token) {
        String[] params = token.split("_");
        if(params.length < 3){
            return null;
        }
        TokenModel tokenModel = new TokenModel();
        tokenModel.setUserId(params[0]);
        tokenModel.setUserType(params[1]);
        tokenModel.setTokenValue(params[2]);
        return tokenModel;
    }

    //获取用户id
    @Override
    public String getUserIdFromToken(String token) {
        TokenModel tokenModel = extractToken(token);
        if (tokenModel == null || StringUtils.isEmpty(tokenModel.getUserId())){
            return null;
        }
        return tokenModel.getUserId();
    }

    //删除token
    @Override
    public boolean deleteToken(String token) {
        String userId = getUserIdFromToken(token);
        if (StringUtils.isEmpty(userId)){
            return false;
        }
        return redisTemplate.delete(Constants.REDIS_PREFIX_TOKEN + userId);
    }
}
